package com.kbbywyclient.ui.activity;

import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.kbbywyclient.R;
import com.kbbywyclient.data.entity.Address;
import com.kbbywyclient.data.entity.BasicInfo;
import com.kbbywyclient.data.model.base.BaseModel;
import com.kbbywyclient.di.AppComponent;
import com.kbbywyclient.di.module.ModifyInfoModule;
import com.kbbywyclient.presenter.ModifyInfoPresenter;
import com.kbbywyclient.ui.activity.base.BaseActivity;
import com.kbbywyclient.ui.adapter.AddressLvAdapter;
import com.kbbywyclient.ui.contarct.ModifyInfoContarct;
import com.kbbywyclient.util.ActivitySkipUtil;
import com.kbbywyclient.util.CheckFormat;
import com.kbbywyclient.util.StringUtil;
import com.kbbywyclient.util.ToastUtil;
import com.kbbywyclient.util.ViewUtils;
import com.kbbywyclient.util.pre.PreUtils;
import com.kbbywyclient.widget.CustomPopwin;
import com.kbbywyclient.widget.CustomToolBar;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Description: 填写资料
 * Created by FHW
 * on 2017/4/7
 */

public class ModifyInfoActivity extends BaseActivity implements ModifyInfoContarct.View {

    @BindView(R.id.v_toolbar)
    CustomToolBar v_toolbar;
    @BindView(R.id.tv_user_name)
    TextView tv_user_name;
    @BindView(R.id.et_username)
    EditText et_username;
    @BindView(R.id.rg_sex)
    RadioGroup rg_sex;
    @BindView(R.id.et_position)
    EditText et_position;
    @BindView(R.id.rg_company_type)
    RadioGroup rg_company_type;
    @BindView(R.id.et_company_name)
    EditText et_company_name;
    @BindView(R.id.tv_province)
    TextView tv_province;
    @BindView(R.id.tv_city)
    TextView tv_city;
    @BindView(R.id.tv_area)
    TextView tv_area;
    @BindView(R.id.et_qq)
    EditText et_qq;
    @BindView(R.id.rl_province)
    RelativeLayout rl_province;
    @BindView(R.id.ll_is_activation_no)
    LinearLayout ll_is_activation_no;
    @BindView(R.id.ll_activation_yes)
    LinearLayout ll_activation_yes;

    //已激活的页面
    @BindView(R.id.tv_user)
    TextView tv_user;
    @BindView(R.id.tv_name)
    TextView tv_name;
    @BindView(R.id.tv_sex)
    TextView tv_sex;
    @BindView(R.id.tv_position)
    TextView tv_position;
    @BindView(R.id.tv_number_type)
    TextView tv_number_type;
    @BindView(R.id.tv_company)
    TextView tv_company;
    @BindView(R.id.tv_address)
    TextView tv_address;
    @BindView(R.id.tv_qq)
    TextView tv_qq;

    private String trueName = "";
    private String sex = "";//性别,1男2女
    private String position = "";
    private String userType = "1";//账户类型,2以公司名义,1以个人名义
    private String companyName = "";
    private String provinceStr = "";
    private String cityStr = "";
    private String distStr = "";
    private String provinceId = "";
    private String cityId = "";
    private String distId = "0";
    private String qq = "";

    private CustomPopwin popProvince;//省
    private CustomPopwin popCity;//市
    private CustomPopwin popArea;//区

    private List<Address> provinceList;
    private AddressLvAdapter provinceLvAdapter;
    private List<Address> cityList;
    private AddressLvAdapter cityLvAdapter;
    private List<Address> areaList;
    private AddressLvAdapter areaLvAdapter;

    @Inject
    ModifyInfoPresenter modifyInfoPresenter;

    private int activation = -1;
    private int modify = -1;

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_modity_info;
    }

    @OnClick({R.id.rl_province, R.id.tv_city, R.id.tv_area, R.id.tv_save, R.id.tv_my_adviser})
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.rl_province:
                if (provinceList.size() <= 0) {
                    modifyInfoPresenter.getAddress("", "", 0);
                }
                rl_province.setBackgroundResource(R.drawable.shape_frame_line_14c095);
                showPopPro(view);
                break;
            case R.id.tv_city:
                if (StringUtil.isNotEmpty(provinceId)) {
                    modifyInfoPresenter.getAddress(provinceId, "", 1);
                } else {
                    ToastUtil.showShort("请选择省份");
                }
                break;
            case R.id.tv_area:
                if (StringUtil.isNotEmpty(cityId)) {
                    modifyInfoPresenter.getAddress(provinceId, cityId, 2);
                } else {
                    ToastUtil.showShort("请选择城市");
                }
                break;
            case R.id.tv_save:
                if (verify()) {
                    modifyInfoPresenter.saveModifyInfo(PreUtils.getUser(this).getSalesID() + "", trueName, sex, position
                            , userType, companyName, provinceId, cityId, distId, qq);
                }
                break;
            case R.id.tv_my_adviser:
                ActivitySkipUtil.skipAnotherActivity(this, MyBusinessConActivity.class);
                break;
        }
    }

    private boolean verify() {
        if (StringUtil.isEmpty(trueName)) {
            ToastUtil.showShort("请输入您的姓名");
            return false;
        }
        if (StringUtil.isEmpty(sex)) {
            ToastUtil.showShort("请选择您的性别");
            return false;
        }
        if (StringUtil.isEmpty(position)) {
            ToastUtil.showShort("请输入您的职位名称");
            return false;
        }
        if (StringUtil.isEmpty(userType)) {
            ToastUtil.showShort("请选择您的账号类型");
            return false;
        }
        if (StringUtil.isEmpty(companyName)) {
            ToastUtil.showShort("请输入您的公司名称");
            return false;
        }
        if (StringUtil.isEmpty(provinceId)) {
            ToastUtil.showShort("请选择省份");
            return false;
        }
        if (StringUtil.isEmpty(cityId)) {
            ToastUtil.showShort("请选择城市");
            return false;
        }
//        if (StringUtil.isEmpty(distId)) {
//            ToastUtil.showShort("请选择区");
//            return false;
//        }
        if (StringUtil.isNotEmpty(qq)) {
            if (!CheckFormat.isQQ(qq)) {
                ToastUtil.showShort("请输入正确的qq号");
                return false;
            }
        }
        return true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        setScreenName("基本资料");
    }

    @Override
    protected void initView() {
        activation = getIntent().getIntExtra("activation", -1);

        provinceList = new ArrayList<>();
        cityList = new ArrayList<>();
        areaList = new ArrayList<>();

        v_toolbar.setLeftViewOnClickLinster(v -> finish());
        rg_sex.setOnCheckedChangeListener((group, checkedId) -> {
            getToolbarFocusable(group);
            switch (checkedId) {
                case R.id.rb_female:
                    sex = "2";
                    break;
                case R.id.rb_man:
                    sex = "1";
                    break;
            }
        });
        rg_company_type.setOnCheckedChangeListener((group, checkedId) -> {
            getToolbarFocusable(group);
            switch (checkedId) {
                case R.id.rb_personal_reg:
                    userType = "1";
                    break;
                case R.id.rb_company_reg:
                    userType = "2";
                    break;
            }
        });

        et_username.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                trueName = s.toString();
            }
        });
        et_position.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                position = s.toString();
            }
        });
        et_company_name.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                companyName = s.toString();
            }
        });

        et_qq.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                qq = s.toString();
            }
        });
    }

    /**
     * 获取焦点并隐藏键盘
     */
    private void getToolbarFocusable(View view) {
        view.setFocusable(true);
        view.setFocusableInTouchMode(true);
        view.requestFocus();
        InputMethodManager imm = (InputMethodManager) getSystemService(this.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
        imm.hideSoftInputFromWindow(et_username.getWindowToken(), 0);
    }

    @Override
    public void initData() {
        ViewUtils.setText(tv_user_name, PreUtils.getUserAccount(this));

        modifyInfoPresenter.getSalesInfo(PreUtils.getUser(this).getSalesID() + "");

    }

    @Override
    public void initAppComponent(AppComponent appComponent) {
        appComponent.getModifyInfoComponent(new ModifyInfoModule(this)).inject(this);
    }

    /**
     * 选择省
     */
    private void showPopPro(View view) {

        View proView = LayoutInflater.from(this).inflate(R.layout.pop_procince, null, false);

        ListView lv_province = (ListView) proView.findViewById(R.id.lv_province);

        provinceLvAdapter = new AddressLvAdapter(this, R.layout.item_address_procince, provinceList);
        lv_province.setAdapter(provinceLvAdapter);

        if (popProvince == null) {
            popProvince = new CustomPopwin(this);
        }
        popProvince.setContentView(proView);
        popProvince.showAsDropDown(view, 0, 0);

        popProvince.setOnDismissListener(() -> rl_province.setBackgroundResource(R.drawable.shape_frame_line_dddddd));

        lv_province.setOnItemClickListener((parent, view1, position1, id) -> {
            provinceStr = provinceList.get(position1).getTitle();
            provinceId = provinceList.get(position1).getID() + "";
            ViewUtils.setText(tv_province, provinceStr.substring(1, provinceStr.length()));
            popProvince.dismiss();
            cityStr = "";
            cityId = "";
            ViewUtils.setText(tv_city, "选择市");
            distStr = "";
            distId = "0";
            ViewUtils.setText(tv_area, "选择区");
        });

    }

    /**
     * 选择市
     *
     * @param view
     */
    private void showPopCity(View view) {
        View proView = LayoutInflater.from(this).inflate(R.layout.pop_city, null, false);

        ListView lv_city = (ListView) proView.findViewById(R.id.lv_city);

        cityLvAdapter = new AddressLvAdapter(this, R.layout.item_address_procince, cityList);
        lv_city.setAdapter(cityLvAdapter);

        if (popCity == null) {
            popCity = new CustomPopwin(this);
        }
        popCity.setContentView(proView);
        popCity.showAsDropDown(view, 0, 0);

        popCity.setOnDismissListener(() -> tv_city.setBackgroundResource(R.drawable.shape_frame_line_dddddd));

        lv_city.setOnItemClickListener((parent, view1, position1, id) -> {
            cityStr = cityList.get(position1).getTitle();
            cityId = cityList.get(position1).getID() + "";
            ViewUtils.setText(tv_city, cityStr.substring(1, cityStr.length()));
            popCity.dismiss();
            distStr = "";
            distId = "0";
            ViewUtils.setText(tv_area, "选择区");
        });
    }

    /**
     * 选择 区
     *
     * @param view
     */
    private void showPopArea(View view) {
        View proView = LayoutInflater.from(this).inflate(R.layout.pop_area, null, false);

        ListView lv_area = (ListView) proView.findViewById(R.id.lv_area);

        areaLvAdapter = new AddressLvAdapter(this, R.layout.item_address_procince, areaList, 0);
        lv_area.setAdapter(areaLvAdapter);

        if (popArea == null) {
            popArea = new CustomPopwin(this);
        }
        popArea.setContentView(proView);
        popArea.showAsDropDown(view, -29, 0, Gravity.LEFT);

        popArea.setOnDismissListener(() -> tv_area.setBackgroundResource(R.drawable.shape_frame_line_dddddd));

        lv_area.setOnItemClickListener((parent, view1, position1, id) -> {
            distStr = areaList.get(position1).getTitle();
            distId = areaList.get(position1).getID() + "";
            ViewUtils.setText(tv_area, distStr);
            popArea.dismiss();
        });
    }


    @Override
    public void showLoadingDialog(String s) {
        showProgress(s);
    }

    @Override
    public void closeLoadingDialog() {
        dismissProgress();
    }

    @Override
    public void loadSucBasicInfo(BasicInfo basicInfo) {

        modify = basicInfo.getModify();

        trueName = basicInfo.getTrueName();
        sex = basicInfo.getSex() + "";
        position = basicInfo.getPosition();
        userType = basicInfo.getUserType() + "";
        companyName = basicInfo.getCompanyName();
        provinceStr = basicInfo.getProvinceName();
        cityStr = basicInfo.getCityName();
        distStr = basicInfo.getDistName();
        if (StringUtil.isNotEmpty(basicInfo.getProvince().toString())) {
            provinceId = new DecimalFormat("0").format(basicInfo.getProvince());
        }
        if (StringUtil.isNotEmpty(basicInfo.getCity().toString())) {
            cityId = new DecimalFormat("0").format(basicInfo.getCity());
        } else {
            cityId = "";
        }
        distId = basicInfo.getDist() + "";
        qq = basicInfo.getQQ();

//        if (activation == 1) {
//            ll_activation_yes.setVisibility(View.VISIBLE);
//            ll_is_activation_no.setVisibility(View.GONE);
//        } else {
//            ll_activation_yes.setVisibility(View.GONE);
//            ll_is_activation_no.setVisibility(View.VISIBLE);
//        }

        if (modify == 1) {//不可修改（激活）
            ll_activation_yes.setVisibility(View.VISIBLE);
            ll_is_activation_no.setVisibility(View.GONE);
            ViewUtils.setText(tv_user, PreUtils.getUserAccount(this));
            ViewUtils.setText(tv_name, trueName);
            switch (sex) {
                case "1.0":
                    ViewUtils.setText(tv_sex, "男");
                    break;
                case "2.0":
                    ViewUtils.setText(tv_sex, "女");
                    break;
            }
            ViewUtils.setText(tv_position, position);
            switch (userType) {
                case "1.0":
                    ViewUtils.setText(tv_number_type, "个人");
                    break;
                case "2.0":
                    ViewUtils.setText(tv_number_type, "公司");
                    break;
                default:
                    ViewUtils.setText(tv_number_type, "个人");
                    break;
            }
            ViewUtils.setText(tv_company, companyName);
            if (StringUtil.isNotEmpty(provinceStr) && StringUtil.isNotEmpty(cityStr)) {
                ViewUtils.setText(tv_address, provinceStr.substring(1, provinceStr.length()) + " " + cityStr.substring(1, cityStr.length())
                        + " " + distStr);
            }
            ViewUtils.setText(tv_qq, qq);

        } else {
            ll_activation_yes.setVisibility(View.GONE);
            ll_is_activation_no.setVisibility(View.VISIBLE);
            et_username.setText(trueName);
            switch (sex) {
                case "1.0":
                    rg_sex.check(R.id.rb_man);
                    break;
                case "2.0":
                    rg_sex.check(R.id.rb_female);
                    break;
            }
            et_position.setText(position);
            switch (userType) {
                case "1.0":
                    rg_company_type.check(R.id.rb_personal_reg);
                    break;
                case "2.0":
                    rg_company_type.check(R.id.rb_company_reg);
                    break;
                default:
                    rg_company_type.check(R.id.rb_personal_reg);
                    break;
            }
            et_company_name.setText(companyName);
            if (StringUtil.isNotEmpty(provinceStr)) {
                ViewUtils.setText(tv_province, provinceStr.substring(1, provinceStr.length()));
            }
            if (StringUtil.isNotEmpty(cityStr)) {
                ViewUtils.setText(tv_city, cityStr.substring(1, cityStr.length()));
            }
            ViewUtils.setText(tv_area, distStr);
            et_qq.setText(qq);

            modifyInfoPresenter.getAddress("", "", 0);
        }

    }

    @Override
    public void loadFaiBasicInfo(String errorMsg) {

    }

    @Override
    public void loadSucAdress(List<Address> addressList, int type) {
        switch (type) {
            case 0://省
                provinceList.addAll(addressList);
                break;
            case 1://市
                cityList.clear();
                cityList.addAll(addressList);
                tv_city.setBackgroundResource(R.drawable.shape_frame_line_14c095);
                showPopCity(tv_city);
                break;
            case 2://区
                areaList.clear();
                areaList.addAll(addressList);
                tv_area.setBackgroundResource(R.drawable.shape_frame_line_14c095);
                showPopArea(tv_area);
                break;
        }
    }

    @Override
    public void loadFaiAdress(String errorMsg) {

    }

    @Override
    public void loadSucSave(BaseModel baseModel) {
        if (StringUtil.isNotEmpty(cityId)) {
            PreUtils.getUser(this).setCity(Integer.valueOf(cityId));
        }
        PreUtils.setCityName(this, cityStr);
//        EventBus.getDefault().post(new Event.SettingUpdate("2"));
        finish();
    }

    @Override
    public void loadFaiSave(String errorMsg) {

    }
}
